<template>
  <div class="container">
    <el-dialog
      :title="TitleText"
      :visible="dialogVisible"
      width="20%"
      @close="btnCancel"
    >
      <el-form
        ref="subjectAddRef"
        :model="subjectAddForm"
        :rules="subjectAddFormRules"
      >
        <el-form-item label="学科名称" prop="subjectName" label-width="80px">
          <el-input v-model="subjectAddForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="subjectAddForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="change"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="end">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects'
export default {
  name: 'subject-add',
  props: {
    dialogVisible: {
      typ: Boolean,
      default: false
    },
    subjectId: {
      type: Number,
      default: null
    }
  },
  computed: {
    TitleText () {
      return this.subjectId ? '修改学科' : '新增学科'
    }
  },
  data () {
    return {
      subjectAddForm: {
        subjectName: '',
        isFrontDisplay: 1
      },
      subjectAddFormRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async btnOk () {
      await this.$refs.subjectAddRef.validate()
      if (!this.subjectId) {
        // 新增操作
        await add(this.subjectAddForm)
      } else {
        // 编辑操作
        this.subjectAddForm = await detail({ id: this.subjectId })
        await update({ subjectID: this.subjectId, tagName: this.subjectAddForm.subjectName })
      }
      this.$emit('getSubjectList')
      this.$emit('update:dialogVisible', false)
    },
    btnCancel () {
      this.subjectAddForm = {
        subjectName: '',
        isFrontDisplay: 1
      }
      this.$refs.subjectAddRef.resetFields()
      this.$emit('update:dialogVisible', false)
    },
    // 开关状态改变时触发
    change (newValue) {
      // console.log(newValue)
      this.subjectAddForm.isFrontDisplay = newValue
      // console.log(this.subjectAddForm.isFrontDisplay)
    }
  }
}
</script>

<style scoped lang="less"></style>
